<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="优惠券名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入优惠券名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择优惠券类型" clearable>
            <el-option label="满减券" value="discount" />
            <el-option label="折扣券" value="percent" />
            <el-option label="无门槛券" value="direct" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="pending" />
            <el-option label="进行中" value="active" />
            <el-option label="已结束" value="ended" />
            <el-option label="已停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="table-wrapper">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增优惠券
          </el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
          <el-button type="warning" :disabled="!selectedIds.length" @click="handleBatchDisable">
            <el-icon><CircleClose /></el-icon>批量停用
          </el-button>
        </div>
      </template>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="couponList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="优惠券名称" prop="name" min-width="150" show-overflow-tooltip />
        <el-table-column label="优惠券类型" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="优惠内容" align="center" width="150">
          <template #default="{ row }">
            <span v-if="row.type === 'discount'">满{{ row.minAmount }}减{{ row.amount }}</span>
            <span v-else-if="row.type === 'percent'">{{ row.amount }}折</span>
            <span v-else>减{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发放数量" prop="totalCount" align="center" width="100" />
        <el-table-column label="已领取" prop="receivedCount" align="center" width="100" />
        <el-table-column label="已使用" prop="usedCount" align="center" width="100" />
        <el-table-column label="有效期" min-width="200">
          <template #default="{ row }">
            <div>{{ row.startTime }} 至 {{ row.endTime }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button link type="primary" @click="handleDetail(row)">
              <el-icon><View /></el-icon>详情
            </el-button>
            <el-button
              link
              :type="row.status === 'disabled' ? 'success' : 'warning'"
              @click="handleToggleStatus(row)"
            >
              <el-icon>
                <component :is="row.status === 'disabled' ? 'CircleCheck' : 'CircleClose'" />
              </el-icon>
              {{ row.status === 'disabled' ? '启用' : '停用' }}
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 优惠券表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="couponFormRef"
        :model="couponForm"
        :rules="couponRules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="couponForm.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="couponForm.type">
            <el-radio label="discount">满减券</el-radio>
            <el-radio label="percent">折扣券</el-radio>
            <el-radio label="direct">无门槛券</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="couponForm.type === 'discount'">
          <el-form-item label="满减金额" prop="minAmount">
            <el-input-number
              v-model="couponForm.minAmount"
              :precision="2"
              :step="10"
              :min="0"
              placeholder="请输入满减金额"
            />
          </el-form-item>
        </template>
        <el-form-item :label="getAmountLabel" prop="amount">
          <el-input-number
            v-if="couponForm.type === 'percent'"
            v-model="couponForm.amount"
            :precision="1"
            :step="0.1"
            :min="0"
            :max="10"
            placeholder="请输入折扣"
          />
          <el-input-number
            v-else
            v-model="couponForm.amount"
            :precision="2"
            :step="1"
            :min="0"
            placeholder="请输入优惠金额"
          />
        </el-form-item>
        <el-form-item label="发放数量" prop="totalCount">
          <el-input-number
            v-model="couponForm.totalCount"
            :min="1"
            :precision="0"
            placeholder="请输入发放数量"
          />
        </el-form-item>
        <el-form-item label="每人限领" prop="perLimit">
          <el-input-number
            v-model="couponForm.perLimit"
            :min="1"
            :precision="0"
            placeholder="请输入每人限领数量"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="validTime">
          <el-date-picker
            v-model="couponForm.validTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="使用说明" prop="description">
          <el-input
            v-model="couponForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入使用说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getCouponList, deleteCoupon, updateCouponStatus } from '@/api/merchant'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  type: '',
  status: ''
})

// 数据列表
const couponList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedIds = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const couponFormRef = ref()
const couponForm = reactive({
  id: undefined,
  name: '',
  type: 'discount',
  minAmount: 0,
  amount: 0,
  totalCount: 100,
  perLimit: 1,
  validTime: [],
  description: ''
})

// 表单校验规则
const couponRules = {
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
  minAmount: [{ required: true, message: '请输入满减金额', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入优惠金额', trigger: 'blur' }],
  totalCount: [{ required: true, message: '请输入发放数量', trigger: 'blur' }],
  perLimit: [{ required: true, message: '请输入每人限领数量', trigger: 'blur' }],
  validTime: [{ required: true, message: '请选择有效期', trigger: 'change' }],
  description: [{ required: true, message: '请输入使用说明', trigger: 'blur' }]
}

// 计算属性
const getAmountLabel = computed(() => {
  const labelMap = {
    discount: '优惠金额',
    percent: '折扣',
    direct: '优惠金额'
  }
  return labelMap[couponForm.type] || '优惠金额'
})

// 获取优惠券列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getCouponList(queryParams)
    couponList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.type = ''
  queryParams.status = ''
  handleQuery()
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增优惠券
const handleAdd = () => {
  dialogTitle.value = '新增优惠券'
  dialogVisible.value = true
  resetForm()
}

// 编辑优惠券
const handleEdit = (row) => {
  dialogTitle.value = '编辑优惠券'
  dialogVisible.value = true
  Object.assign(couponForm, {
    ...row,
    validTime: [row.startTime, row.endTime]
  })
}

// 查看详情
const handleDetail = (row) => {
  router.push(`/merchant/marketing/coupon-detail/${row.id}`)
}

// 删除优惠券
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该优惠券吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCoupon(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除优惠券失败:', error)
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的优惠券')
    return
  }
  ElMessageBox.confirm(`确认要删除选中的 ${selectedIds.value.length} 个优惠券吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await Promise.all(selectedIds.value.map(id => deleteCoupon(id)))
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除优惠券失败:', error)
    }
  })
}

// 切换优惠券状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 'disabled' ? 'active' : 'disabled'
  try {
    await updateCouponStatus(row.id, newStatus)
    ElMessage.success(`${newStatus === 'active' ? '启用' : '停用'}成功`)
    getList()
  } catch (error) {
    console.error('更新优惠券状态失败:', error)
  }
}

// 批量停用
const handleBatchDisable = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要停用的优惠券')
    return
  }
  ElMessageBox.confirm(`确认要停用选中的 ${selectedIds.value.length} 个优惠券吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await Promise.all(selectedIds.value.map(id => updateCouponStatus(id, 'disabled')))
      ElMessage.success('批量停用成功')
      getList()
    } catch (error) {
      console.error('批量停用优惠券失败:', error)
    }
  })
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 表单相关
const resetForm = () => {
  if (couponFormRef.value) {
    couponFormRef.value.resetFields()
  }
  Object.assign(couponForm, {
    id: undefined,
    name: '',
    type: 'discount',
    minAmount: 0,
    amount: 0,
    totalCount: 100,
    perLimit: 1,
    validTime: [],
    description: ''
  })
}

// 提交表单
const submitForm = async () => {
  if (!couponFormRef.value) return
  await couponFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const [startTime, endTime] = couponForm.validTime
        const data = {
          ...couponForm,
          startTime,
          endTime
        }
        delete data.validTime
        // TODO: 调用保存优惠券接口
        ElMessage.success('保存成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('保存优惠券失败:', error)
      }
    }
  })
}

// 状态相关方法
const getTypeTag = (type) => {
  const typeMap = {
    discount: 'success',
    percent: 'warning',
    direct: 'info'
  }
  return typeMap[type] || 'info'
}

const getTypeText = (type) => {
  const typeMap = {
    discount: '满减券',
    percent: '折扣券',
    direct: '无门槛券'
  }
  return typeMap[type] || '未知'
}

const getStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    active: 'success',
    ended: 'warning',
    disabled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '未开始',
    active: '进行中',
    ended: '已结束',
    disabled: '已停用'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-wrapper {
    margin-bottom: 20px;
  }

  .table-wrapper {
    .card-header {
      display: flex;
      gap: 10px;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 